package com.zheng.api.server.service.mq.um;

import com.zheng.api.server.service.base.um.Base4UmbrellaService;
import com.zheng.common.constant.MqConstant;
import org.apache.activemq.ScheduledMessage;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.jms.*;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @Description: 伞机通知MQ统一处理
 * @author lvb
 * @date 2017-10-31
 * @version V1.0
 * @Copyright:
 */
@Service
public class Mq4UmbrellaMachine extends Base4UmbrellaService {

    @Autowired
    private JmsTemplate jmsTopicTemplate;
    private static final Logger LOGGER = LoggerFactory.getLogger(Mq4UmbrellaMachine.class);
    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 按频道发送
     * @param topic
     * @param msg
     */
    public void send(Topic topic, String msg) {
        LOGGER.info("发送MQ消息:msg={}", msg);
        jmsTopicTemplate.convertAndSend(topic, msg);
    }

    /**
     * 按频道或指定客户端发送
     * 发送延迟消息
     * @param topic
     * @param msg
     * @param delay
     * @param clientId
     */
    public void send(final Topic topic,final String msg, final long delay,final String clientId) {
        LOGGER.info("向伞机端发送MQ延时消息:msg={},delay={}", msg, delay);
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                jmsTopicTemplate.send(topic, new MessageCreator() {
                    public Message createMessage(Session session) throws JMSException {
                        TextMessage tm = session.createTextMessage(msg);
                        tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
                        tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 1*1000);
                        tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 0);
                        if(StringUtils.isNotEmpty(clientId)){
                           tm.setStringProperty(MqConstant.PTP_CLIENTID,clientId);
                        }
                        return tm;
                    }
                });
            }
        });
    }

    private static class TrustAnyTrustManager implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    }

    public String httpPost(String url) {
        StringBuffer sb = new StringBuffer();
        try {
            URL console = new URL(url);
            if("https".equals(console.getProtocol())) {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
                        new java.security.SecureRandom());
                HttpsURLConnection con = (HttpsURLConnection) console.openConnection();
                con.setSSLSocketFactory(sc.getSocketFactory());
                con.setRequestMethod("POST");
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setUseCaches(false);
                con.setConnectTimeout(30 * 1000);
                con.setReadTimeout(60 * 1000);
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()), 1024*1024);
                while (true) {
                    String line = in.readLine();
                    if (line == null) {
                        break;
                    }
                    sb.append(line);
                }
                in.close();
            }else if("http".equals(console.getProtocol())) {
                HttpURLConnection con = (HttpURLConnection) console.openConnection();
                con.setRequestMethod("POST");
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setUseCaches(false);
                con.setConnectTimeout(30 * 1000);
                con.setReadTimeout(60 * 1000);
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()), 1024*1024);
                while (true) {
                    String line = in.readLine();
                    if (line == null) {
                        break;
                    }
                    sb.append(line);
                }
                in.close();
            }else {
                LOGGER.error("not do protocol. protocol=%s", console.getProtocol());
            }
        } catch(Exception e) {
            LOGGER.error( "httpPost exception. url:%s", url,e);
        }
        return sb.toString();
    }

}
